import java.util.regex.Pattern;

import org.owasp.esapi.ESAPI;

public class NegativeLookaheadExample {
	private static final Pattern[] patterns = new Pattern[]{
			// Script fragments
			Pattern.compile("<script>(.*?)</script>", Pattern.CASE_INSENSITIVE),
			// src='...'
			Pattern.compile("src[\r\n]*=[\r\n]*\"([^\"]*(?<!\\.jpg|png|gif|jpeg))\"", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL), // Escape All src="*" (but keep images)
			Pattern.compile("src[\r\n]*=[\r\n]*'([^']*(?<!\\.jpg|png|gif|jpeg))'", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL), // Escape All src='*' (but keep images)
			// lonely script tags
			Pattern.compile("</script>", Pattern.CASE_INSENSITIVE),
			Pattern.compile("<script(.*?)>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL),
			// eval(...)
			Pattern.compile("eval\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL),
			// expression(...)
			Pattern.compile("expression\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL),
			// javascript:...
			Pattern.compile("javascript:", Pattern.CASE_INSENSITIVE),
			// vbscript:...
			Pattern.compile("vbscript:", Pattern.CASE_INSENSITIVE),
			// onload(...)=...
			Pattern.compile("onload(.*?)=", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL)
	};
  public static void main(String args[]) throws Exception {

	String clearedValue = "<p>C&#39;est Martin ! <em><strong>Dieu de Liber</strong></em> !<img alt=\"\" " +
			"src=\'test.js\'A/><img alt=\"\" src=\'test.swf\'A/><img alt=\"\" src=\'test.jpg\'A/><img alt=\"\"" +
			" src=\"test.png\"A/> Hello  dddd</p><SCRIPT SRC=\"http://ha.ckers.org/xss.jpg\"></SCRIPT>";
    // NOTE: It's highly recommended to use the ESAPI library and uncomment the following line to
    // avoid encoded attacks.
	clearedValue = ESAPI.encoder().canonicalize(clearedValue);

    // Avoid null characters
	clearedValue = clearedValue.replaceAll("\0", "");

    // Remove all sections that match a pattern
    for (Pattern scriptPattern : patterns){
    	clearedValue = scriptPattern.matcher(clearedValue).replaceAll("");
    	System.out.println(clearedValue);
    }

  }
}